package org.agpsoft.simpledatareceiver;

import java.io.IOException;
import java.io.OutputStream;

import org.agpsoft.datareceiverinfrastructure.common.IDecodedData;
import org.agpsoft.datareceiverinfrastructure.common.RawData;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverCloseException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverNULLObjectException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverOpenException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverTransmitException;
import org.agpsoft.datareceiverinfrastructure.transmitter.IDataTransmitter;

public class SimpleDataTransmitter implements IDataTransmitter {

	private OutputStream outStream = null;
	
	@Override
	public int sendData(IDecodedData data)
			throws DataReceiverTransmitException,
			DataReceiverNULLObjectException {
		if( data == null )
		{
			throw new DataReceiverNULLObjectException();
		}
		
		RawData rawData = new RawData();
		data.getRawPresentation( rawData );
		try {
			outStream.write( rawData.getData() );
		} catch (IOException e) {
			throw new DataReceiverTransmitException();
		}
		
		return rawData.getData().length;
	}

	@Override
	public void close() throws DataReceiverCloseException {
	}

	@Override
	public void open(Object context) throws DataReceiverOpenException {
		SimpleDataReceiverContext tcpContext = 
			(SimpleDataReceiverContext) context;
		outStream = tcpContext.getOutputStream();
	}

}
